// miniprogram/pages/order/add.js
import * as R from 'ramda';
import U from '../../utils/index';
import WxValidate from '../../utils/vendor/WxValidate.js';
import dayjs from 'dayjs';
const validator = {
  rules: {
    rent_end_date: {
      required: true,
    },
    change_date: {
      required: true,
    },
  },
  messages: {
     rent_end_date: {
       required: '请选择续费结束日期',
     },
     change_date: {
       required: '请选择滤芯更换时间',
     },
  }
};
const wxValidate = new WxValidate(validator.rules, validator.messages);

const handleRequestUpdateForm = U.reqPostShow('/order/update', '续费订单成功！');

// 日期不为空就转化为时间戳
const changeTimeStamp = R.unless(R.isNil, date => dayjs(date).toDate().getTime());

Page({

  /**
   * 页面的初始数据
   */
  data: {
    form: {},
    aliasForm: {},
    datePickerData: {
      isShowRentEndDate: false,
      isShowChangeDate: false,
    },
    currentDate: new Date().getTime(),
    minDate: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      minDate: changeTimeStamp(U.getPrevPage().data.pageData.rent_end_date),
      ['form.order_id']: Number(options.orderId),
      ['form.order_type']: 1
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  onSubmit() {
    R.compose(
      U.runIO,
      U.handleError,
      R.map(
        R.compose(
          U.fork,
          R.map(
            R.compose(
              U.runIO,
              U.backReqSuc,
            )
          ),
          handleRequestUpdateForm
        )
      ),
      U.validate(wxValidate),
      R.tap(form => this.setData({ form })),
      R.map(U.trim),
    )(this.data.form);
  },
  setFormData(e) {
    U.setFormData(e).run(this);
  },
  switchRentEnd() {
    this.setData({
      [ 'datePickerData.isShowRentEndDate' ]: !this.data.datePickerData.isShowRentEndDate,
    })
  },
  onConfirmRentEnd(e) {
    this.setData({
      [ 'form.rent_end_date' ]: dayjs(e.detail).format('YYYY-MM-DD'),
      [ 'aliasForm.rent_end_date' ]: e.detail,
      [ 'datePickerData.isShowRentEndDate' ]: false,
    })
  },
  switchChangeDate(e) {
    this.setData({
      [ 'datePickerData.isShowChangeDate' ]: !this.data.datePickerData.isShowChangeDate,
    })
  },
  onConfirmChangeDate(e) {
    this.setData({
      [ 'form.change_date' ]: dayjs(e.detail).format('YYYY-MM-DD'),
      [ 'aliasForm.change_date' ]: e.detail,
      [ 'datePickerData.isShowChangeDate' ]: false,
    })
  },
});
